<template>
  <div class="form-container">
    <!-- 打印机连接状态 -->
    <van-field
      v-model="orderNumber"
      label="连接状态"
      placeholder="打印机连接状态"
    />
    
    <!-- 料号 -->
    <van-field
      v-model="materialNumber"
      label="料号"
      placeholder="请输入料号"
    />
    
    <!-- 版本 -->
    <van-field
      v-model="version"
      label="版本"
      placeholder="请输入版本"
    />
    
    <!-- 数量 -->
    <van-field
      v-model="quantity"
      type="digit"
      label="数量"
      placeholder="请输入数量"
    />
    
    <!-- 入库日期 -->
    <van-field
      v-model="storageDate"
      is-link
      readonly
      label="入库日期"
      placeholder="请选择日期"
      @click="showDatePicker = true"
    />
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        v-model="currentDate"
        @confirm="onConfirmDate"
        @cancel="showDatePicker = false"
      />
    </van-popup>
    
    <!-- 入库单号 -->
    <van-field
      v-model="storageNumber"
      label="入库单号"
      placeholder="请输入入库单号"
    />
    
    <!-- 图片上传和选择 -->
    <div class="image-upload">
      <van-button 
        type="default" 
        size="small"
        @click="handleTakePhoto"
      >
        拍照
      </van-button>
      <img 
        v-if="capturedImage" 
        :src="capturedImage" 
        style="max-width: 200px; max-height: 200px; display: block;"
      />
    </div>
    
    <!-- 提交按钮 -->
    <div class="submit-btn">
      <van-button 
        type="primary" 
        color="#07c160"
        block
        @click="handleSubmit"
      >
        打印入库标签
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { showToast } from 'vant';

import { 
  updateVlaue
} from './utils/orderUtils.js';


const orderNumber = ref('');
const materialNumber = ref('');
const version = ref('');
const quantity = ref('');
const storageDate = ref('');
const storageNumber = ref('');
const showDatePicker = ref(false);
const currentDate = ref([new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]);

const onConfirmDate = ({ selectedValues }) => {
  storageDate.value = selectedValues.join('/');
  showDatePicker.value = false;
};

const handleLoad = () => {
  //updateVlaue(orderNumber, '页面加载完成');
  document.addEventListener(
    "deviceready",
    function () {
      // 在这里使用 MyPlugin
      console.log(`[PDAScanner]typeof MyPlugin:${typeof MyPlugin}`);
      if (typeof MyPlugin !== "undefined") {
        //showToast('doMyPlugin');
        setInterval(() => {
          MyPlugin.callMyMethod(
            "Hello from JavaScript",
            "getConnectStatus",
            function (result) {
              console.log(result);
              //showToast(result);
              let data = JSON.parse(result);
              if (data.success) {
                updateVlaue(orderNumber, data.msg);
              }
            },
            function (error) {
              showFailToast(error);
              console.error("Error: ", error);
            }
          );
        }, 1000);
      } else {
        showFailToast("MyPlugin is not available");
      }

      //==============

      console.log(`[PDAScanner]typeof PDAScanner:${typeof PDAScanner}`);
      // 在这里使用 PDAscanner
      if (typeof PDAScanner !== "undefined") {
        showToast("doPPDAScanner2");
        setInterval(() => {
          PDAScanner.callPDAscanner(
            "Hello from JavaScript",
            "pluginInitialize",
            function (result) {
              console.log(result);
              //showToast(result);
              let data = JSON.parse(result);
              if (data.success) {
                updateVlaue(materialNumber, data.msg);
              }
            },
            function (error) {
              showFailToast(error);
              console.error("Error: ", error);
            }
          );
        }, 1000);
      } else {
        showFailToast("PDAScanner is not available");
      }

      //==============

      console.log(`[PDAScanner]typeof QRscanner:${typeof QRscanner}`);
      // 在这里使用 PDAscanner
      if (typeof QRscanner !== "undefined") {
        showToast("doPPDAScanner3");
        setInterval(() => {
          QRscanner.callQRscanner(
            "Hello from JavaScript",
            "pluginInitialize",
            function (result) {
              console.log(result);
              //showToast(result);
              let data = JSON.parse(result);
              if (data.success) {
                updateVlaue(version, data.msg);
              }
            },
            function (error) {
              showFailToast(error);
              console.error("Error: ", error);
            }
          );
        }, 1000);
      } else {
        showFailToast("PDAScanner is not available");
      }
    },
    false
  );
};

onMounted(() => {
  handleLoad();
});

const handleSubmit = () => {
  //showToast('已打印');
  /*MyPlugin.callMyMethod('Hello from JavaScript','myMethod',
            function(result) {
                console.log(result);
                showToast(result);
            },
            function(error) {
                showFailToast(error);
                console.error('Error: ', error);
            }
  );*/
  PDAscanner.callPDAscanner('Hello from JavaScript','pluginInitialize',
            function(result) {
                console.log(result);
                //showToast(result);    
                let data = JSON.parse(result);
                if(data.success){
                  updateVlaue(materialNumber, data.msg);
                }
            },
            function(error) {
                showFailToast(error);
                console.error('Error: ', error);
            }
        );
};
const capturedImage = ref('');
const fileList = ref([]);

const handleTakePhoto = () => {
  if (typeof navigator.camera === 'undefined') {
    showToast('请在移动设备上使用此功能');
    return;
  }

  navigator.camera.getPicture(
    (imageData) => {
      // 修改为
      console.log(`[MyPlugin]imageData:${imageData}`)
      // 检查imageData是否已经是Base64格式
      if (!imageData.startsWith('data:image/')) {
        imageData = `data:image/jpeg;base64,${imageData}`;
      }
      capturedImage.value = imageData;
    },
    (message) => {
      showToast('拍照失败: ' + message);
    },
    {
      quality: 50,
      destinationType: Camera.DestinationType.DATA_URL,
      encodingType: Camera.EncodingType.JPEG,
      mediaType: Camera.MediaType.PICTURE,
      correctOrientation: true
    }
  );
};
</script>

<style scoped>
.form-container {
  padding: 16px;
}

.image-upload {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.image-upload .van-uploader {
  margin-right: 8px;
}

.submit-btn {
  margin-top: 24px;
}

.preview-image {
  max-width: 100px;
  max-height: 100px;
  margin-left: 10px;
  border-radius: 4px;
}
</style>